package com.jjty.dataGenerator.jshjy.utils;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.crypto.digest.HmacAlgorithm;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import com.jjty.dataGenerator.jshjy.entity.JsCallData;
import com.jjty.dataGenerator.jshjy.entity.JsLocationData;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

/**
 * Created by liuliang on 2025/6/12.
 */
@Slf4j
public class SignUtils {
    public static String generateSignature(String bodyJson, String nonce, String timestamp, String appSecret) {

        // 对 body 做 MD5（可选 "" 处理空体）
        String bodyMd5 = DigestUtil.md5Hex(StringUtils.isEmpty(bodyJson) ? "" : bodyJson);
        // 构造签名参数 Map
        Map<String, String> signParams = Maps.newTreeMap();
        signParams.put("body", bodyMd5);
        signParams.put("nonce", nonce);
        signParams.put("timestamp", timestamp);
        signParams.put("appSecret", appSecret);
        //按 key 排序拼接为 key=value&key2=value2...
        String paramStr = signParams.entrySet().stream()
                .map(e -> e.getKey() + "=" + e.getValue())
                .collect(Collectors.joining("&"));
        //使用appSecret作为 hmac key
        return SecureUtil.hmac(HmacAlgorithm.HmacSHA256, appSecret.getBytes()).digestHex(paramStr);
    }

    public static boolean verifySignature(String bodyJson, String nonce, String timestamp, String appSecret, String sign) {
        String actualSign = generateSignature(bodyJson, nonce, timestamp, appSecret);
        return actualSign.equalsIgnoreCase(sign);
    }
    private static String sortRequestBody(String bodyJson) {
        if (StringUtils.isEmpty(bodyJson)) {
            return "";
        }
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            // 将 JSON 字符串解析为 Map
            Map<String, Object> bodyMap = objectMapper.readValue(bodyJson, HashMap.class);
            // 使用 TreeMap 对键进行字典顺序排序
            Map<String, Object> sortedMap = new TreeMap<>(bodyMap);
            // 将排序后的 Map 转换回 JSON 字符串
            return objectMapper.writeValueAsString(sortedMap);
        } catch (Exception e) {
            log.error("Failed to sort request body: {}", e.getMessage());
            return bodyJson;
        }
    }

    public static void main(String[] args) {
        String bodyJson2 = "{\"schoolId\":\"100001\",\"cardNo\":\"888888888888\",\"gradeId\":\"0\",\"gradeName\":\"初二年级\",\"classId\":\"0\",\"className\":\"5班\",\"studentId\":\"0\",\"studentName\":\"王砚博\",\"position\":\"校门口\"," +
                "\"passageTime\":\"2025-06-18 07:29:19\",\"passageType\":\"1\"}";
        JsCallData zybDeviceState = new JsCallData();
        zybDeviceState.setChannel("XFY");
        zybDeviceState.setImeiNo("862074063050571");
        zybDeviceState.setCallTime("2025-07-24 12:28:21");
        zybDeviceState.setPhoneNo("13908762051");
        zybDeviceState.setDuration("109");
        zybDeviceState.setRemainingDuration("5603");
        String bodyJson = JsonUtils.toJsonString(zybDeviceState);
        System.out.println("bodyJson:"+bodyJson);
        String nonce = IdUtil.fastUUID();
        String timestamp = String.valueOf(System.currentTimeMillis());
        String appSecret = "g8jeX6byH6cCp5ac";
        String signature = generateSignature(bodyJson, nonce, timestamp, appSecret);
        System.out.println("nonce :" + nonce);
        System.out.println("timestamp :" + timestamp);
        System.out.println("generateSignature :" + signature);
        System.out.println("verifySignature :" + verifySignature(bodyJson, nonce, timestamp, appSecret, signature));

    }
}
